<?php

namespace Aiweline\WebpConverter\Controller;

use WebPConvert\WebPConvert;
use Weline\Framework\App\Exception;
use Weline\Framework\Manager\ObjectManager;
use Weline\Framework\System\File\Uploader;

class Index extends \Weline\Framework\App\Controller\FrontendController
{
    public function index()
    {
        if ($this->_request->isPost()) {
            try {
                /**@var Uploader $uploader */
                $uploader = ObjectManager::getInstance(Uploader::class);
                $image = $uploader->addAcceptOriginDomain(['http://weline.com'])
                    ->saveFiles();
                $source = str_replace('/', DS, BP . $image[0]);
                $destination = rtrim($source, pathinfo($source, PATHINFO_EXTENSION)) . 'webp';
                $options = [];
                WebPConvert::convert($source, $destination, $options);
                $this->assign('download', str_replace(BP, '', $destination));
                $this->assign('name', pathinfo($destination, PATHINFO_BASENAME));
                $uploader->delete(pathinfo($source, PATHINFO_BASENAME));
            } catch (\Exception $e) {
                $this->assign('error', __('文件上传错误：') . $e->getMessage());
            }
        }
        return $this->fetch();
    }
}
